import React from 'react';
import { createBehavior, createResource } from '@inbiz/core';
import TableDesigner from '../../preview/web/index';
import { DnFC } from '@inbiz/react';
import {
  createBaseSchema,
  createComponentStyleSchema,
  createDecoratorStyleSchema,
  createInbizSchema,
  createSoureSchema,
  createRelationSchema,
  createComponentLayout,
  createControllerSchema,
} from '@inbiz/setters';
import * as Schema from './schema';
import { TableStyle } from './schema';
import * as Locale from '../locale';
import {
  ActionEnum,
  ActionPosition,
  Actions,
  ActionTypeMap,
  ActionTypeObj,
  Option,
  UnitEnum,
} from '../../shared';
import MyAutoComplete from '@components/form/base/EformInput/designer/components/MyAutoComplete';
import { uuid } from '@inbiz/utils';
import type { Field } from '@formily/core';

const SubTable: DnFC<React.ComponentProps<typeof TableDesigner>> = TableDesigner;

const createSchema = (name: string) => {
  return createInbizSchema({
    attribute: {
      ...createBaseSchema(Schema[name], undefined, true),
      ...createRelationSchema(
        {
          range: 'current',
          filter: 'SubTable',
        },
        {
          relationField: {
            type: 'string',
            'x-decorator': 'FormItem',
            'x-component': MyAutoComplete,
            'x-reactions': {
              dependencies: [
                // 'form.senior.soure.sourceModelUpdate',
                'form.senior.x-component-props.model',
                // 'form.attribute.base.x-component-props.search',
              ],

              fulfill: {
                // state: {
                //   visible: '{{$deps[1] == true}}',
                // },
                schema: {
                  //@ts-ignore
                  'x-component-props.update': '{{$deps[0]}}',
                  'x-component-props.valueType': 'value',
                  'x-component-props.syncModel': `{{$deps[0].Name}}`,
                  // 'x-hidden':'{{!$deps[1]}}'
                },
              },
            },
          },
        },
      ),
    } as any,
    style: {
      ...createComponentStyleSchema(TableStyle),
      ...createComponentLayout(),
      ...createDecoratorStyleSchema(),
    },
    senior: {
      'x-component-props': {
        type: 'object',
        properties: {
          model: {
            type: 'object',
            'x-decorator': 'FormItem',
            'x-component': 'ChooseModuleEngine',
            'x-component-props': {
              page: true,
            },
            // 解决模型更新查询数据源没有更新的问题。
            'x-reactions': {
              effects: ['onFieldInputValueChange'],
              fulfill: {
                run: `$form.query(/sourceModel$/).take().value = undefined;`,
              },
            },
          },
        },
      },
      ...createSoureSchema(
        {
          isApi: false,
          fieldChange: (form, value) => {
            if (!value?.isChangeModel) {
              return;
            }
            const targetList = form.query(/searchField$/).take() as Field;
            const columnConfig = form.query(/columnConfig$/).take() as Field;
            // const relationField = form.query(/relationField$/).take() as Field;
            const fielList: Array<string> = (value as any)?.queryField?.map(
              (ele: any) => ele.AnotherName || ele.FieldName.split('$')[1],
            );
            const searchFieldValue = targetList.value?.filter((ele: string) =>
              fielList.some((child: string) => child === ele),
            );
            const attrTable = columnConfig.value?.tableValues?.attrs;
            const attrTableList = attrTable?.filter((ele: any) =>
              fielList.some((child: string) => child === ele.propName),
            );
            targetList.value = searchFieldValue;
            columnConfig.value.tableValues.attrs = fielList.map((ele, index) => ({
              propName: ele,
              visible: '1',
              width: 100,
              columnName: (value as any)?.queryField[index].ColName
            }));

            // relationField.value = relationFieldValue;
          },
          config: {
            modelReadOnly: true,
            aliasConfig: {
              readonly: true,
            },
          },
        },
        ['search'],
      ),
    },
    controller: createControllerSchema({
      events: [
        {
          name: "onOpen",
          label: "弹框打开事件",
          platform: 'web'
        },
        {
          name: "onClose",
          label: "弹框关闭事件",
          platform: 'web'
        },
        {
          name: "onAdd",
          label: "数据添加事件",
          platform: 'web'
        },
        {
          name: "onEdit",
          label: "数据修改事件",
          platform: 'web'
        },
        {
          name: "onSuccess",
          label: "数据请求成功事件",
          platform: 'web'
        },
        {
          name: "onError",
          label: "数据请求失败事件",
          platform: 'web'
        },
        {
          name: "onClick",
          label: "单击事件",
          platform: 'web'
        },
        {
          name: "onDblClickRow",
          label: "双击行事件",
          platform: 'web'
        },
        {
          name: "onBeforeOpen",
          label: "弹框打开前回调事件",
          isConfigEvent: true,
          platform: 'web'
        },
        {
          name: "onBeforeClose",
          label: "弹框关闭前回调事件",
          isConfigEvent: true,
          platform: 'web'
        },
        {
          name: "onColumnsFormat",
          label: "列格式化",
          isConfigEvent: true,
          platform: 'web'
        },
        {
          name: "onOperateFormat",
          label: "操作列格式化",
          isConfigEvent: true,
          platform: 'web'
        },
        {
          name: "onBeforeOperationAsync",
          label: "新增/编辑/删除前执行",
          isConfigEvent: true,
          platform: 'web'
        },
        {
          name: "onInitQueryParams",
          label: "新增/编辑/删除前执行",
          isConfigEvent: true,
          platform: 'web'
        }]
    })
  });
};

export const defaultTableProps = {
  showLineNumber: true,
  resizeColumnWidth: true,
  autoLoad: true,
  search: false,
  rowSelection: false,
  importUpdate: false,
  size: 'small',
  rowHeight: 'middle',
  readOnly: false,
  columnConfig: {
    formItems: {
      fixedActionColumn: 'right',
      actionColumnWidth: 200,
      toolbarDisplayQty: 3,
      actionDisplaySetup: 'text',
      tableHeaderBtnShow: 'text',
      inLineBtnShow: 'text',
      toolbarDisplayPosition: 'left',
      pageSize: 999,
      widthUnit: UnitEnum.percentage,
      width: {
        widowWidth: 60,
        widthSuffix: UnitEnum.percentage,
      },
      height: {
        windowHeight: 60,
        heightSuffix: UnitEnum.percentage,
      },
      authControl: true,
      actionPanelWidth: 200,
    },
    tableValues: {
      actions: Actions().reduce((data: any[], action) => {
        if (
          ![ActionEnum.add, ActionEnum.view, ActionEnum.edit].includes(action.value as ActionEnum)
        ) {
          return data;
        }
        data.push({
          id: uuid(5, 5),
          actionType: action.value,
          actionName: action.label,
          position:
            action.value === ActionEnum.add ? ActionPosition.tableHeader : ActionPosition.inline,
          openMode: 'modal',
          windowName: action.label,
          show: true
        });
        return data;
      }, []),
      subWindow: Option().parentAction.reduce((data: any[], action) => {
        ActionTypeMap[action.value].forEach((type: ActionEnum) => {
          if (type === ActionEnum.custom) {
            return;
          }
          data.push({
            id: uuid(5, 5),
            parentAction: action.value,
            actionType: type,
            actionName: ActionTypeObj[type].label,
          });
        });
        return data;
      }, []),
    },
  },
};

SubTable.Behavior = createBehavior({
  name: 'SubTable',
  extends: ['Field'],
  selector: (node) => node.props?.['x-component'] === 'SubTable',
  designerProps: {
    droppable: true,
    propsSchema: createSchema('SubTable'),
  },
  designerLocales: Locale.SubTable,
});

SubTable.Resource = createResource({
  icon: 'SubTable',
  elements: [
    {
      componentName: 'Field',
      props: {
        type: 'void',
        title: {
          value: 'SubTable.title',
          status: true,
        },
        'x-decorator': 'FormItem',
        'x-decorator-props': {
          style: {
            padding: '0px 20px 0px 20px',
          },
        },
        'x-component': 'SubTable',
        'x-component-props': defaultTableProps,
      },
    },
  ],
});

export default SubTable;
